import React from "react";
import { useForm } from "react-hook-form";
import { useRequest } from "ahooks";
import dayjs from "dayjs";
import { Button } from "@/components/ui/button";
import request from "@/api/http_class";
import { Heading } from "@/components/ui/heading";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { zodResolver } from "@hookform/resolvers/zod";
import { ColumnDef, createColumnHelper } from "@tanstack/react-table";
import { ArrowUpDown, CalendarIcon } from "lucide-react";
import { Edit, MoreHorizontal, Trash } from "lucide-react";
import * as z from "zod";
import { AlertModal } from "@/components/modal/alert-modal";
import { RootStateI, VbpDayStatsI } from "@/types";
import PageContainer from "@/components/layout/page-container";
import CustomDndTable from "@/components/ui/custom-dnd-table";
import { useToast } from "@/hooks/use-toast";
import { Plus } from "lucide-react";
import { generateVbpStatsList, searchVbpStatsList } from "@/api";
import { useSearchParams, Link } from "react-router-dom";
import { CustomDatePicker } from "@/components/ui/datepicker";
import { hasPermission } from "@/lib/utils";
import { useSelector } from "react-redux";

const formSchema = z.object({
  startDate: z.date({ required_error: "请输入查询开始时间" }),
  endDate: z.date({ required_error: "请输入查询结束时间" }),
  hisCode: z.string().trim(),
});

type FormValuesT = z.infer<typeof formSchema>;

const page: React.FC = () => {
  const [searchParams] = useSearchParams();
  const { toast } = useToast();
  const user = useSelector((state: RootStateI) => state.user);

  const [title, setTitle] = React.useState<string>("");
  const [description, setDescription] = React.useState<string>("");
  const [isSubmitting, setIsSubmitting] = React.useState<boolean>(false);
  const [isAlertOpen, setIsAlertOpen] = React.useState<boolean>(false);
  const [isDialogOpen, setIsDialogOpen] = React.useState<boolean>(false);
  const [totalCount, setTotalCount] = React.useState<number>(0);
  const [vbpBatchList, setVbpStatsList] = React.useState<VbpDayStatsI[]>([]);
  const [formData, setFormData] = React.useState<VbpDayStatsI>();

  const { loading: loadingList, run } = useRequest(
    (paramsString: string) => searchVbpStatsList(paramsString),
    {
      manual: true,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp, params: any) {
        // console.log(params);
        console.log(resp.data.data);
        setVbpStatsList(resp.data.data);
        setTotalCount(resp.data.totalCount);
      },
      onError(e: any, params: any) {
        console.error("获取数据失败");
        toast({
          variant: "destructive",
          title: "数据获取失败",
          description: "请检查网络或联系系统管理员",
        });
      },
    }
  );

  const handleUploadSubmit = (values: any): Promise<any> => {
    console.log(values);
    return new Promise((resolve, reject) => {
      if (values.files.length) {
        const formData = new FormData();
        // 将全部数据转换为FormData格式
        values.files.forEach((item: File) => {
          console.log(item);
          formData.append("files", item);
        });
        console.log(formData);
        request({
          // url: `/vbp-stats/import/`,
          url: `/vbp-stats/bulk/`,
          method: "POST",
          data: formData,
          headers: { "Content-Type": "multipart/form-data" },
        }).then(
          (res: any) => {
            console.log(res);
            resolve(res);
            toast({
              variant: "success",
              title: "数据导入成功",
              description: "",
            });
          },
          (err: any) => {
            console.log(err);
            reject(err);
            toast({
              variant: "destructive",
              title: "数据导入失败",
              description: "请检查网络或联系系统管理员",
            });
          }
        );
      } else {
        reject("no files");
      }
    });
  };

  React.useEffect(() => {
    // console.log(searchParams);
    run(searchParams.toString());
    console.log("count");
  }, [searchParams]);

  const columnHelper = createColumnHelper<VbpDayStatsI>();

  const columns = [
    columnHelper.display({
      id: "select",
      header: (props) => {
        // console.log(props);
        if (props && props.table) {
          return (
            <Checkbox
              checked={props.table.getIsAllPageRowsSelected()}
              onCheckedChange={(value) =>
                props.table.toggleAllPageRowsSelected(!!value)
              }
              aria-label="Select all"
            />
          );
        } else {
          return <Checkbox aria-label="Select all" />;
        }
      },
      footer: (props) => props.column.id,
      cell: (props) => {
        if (props && props.row) {
          return (
            <Checkbox
              checked={props.row.getIsSelected()}
              onCheckedChange={(value) => props.row.toggleSelected(!!value)}
              aria-label="Select row"
            />
          );
        } else {
          return <Checkbox aria-label="Select row" />;
        }
      },
      enableSorting: false,
      enableHiding: true,
    }),
    columnHelper.accessor("id", {
      id: "id",
      header: "ID",
      cell: ({ row }) => {
        return <span>{row.getValue("id")}</span>;
      },
      enableSorting: false,
      enableHiding: false,
    }),
    columnHelper.accessor("statsDate", {
      id: "statsDate",
      header: "统计时间",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          if (!isNaN(Date.parse(row.getValue("statsDate")))) {
            return (
              <span>
                {dayjs(row.getValue("statsDate")).format("YYYY-MM-DD")}
              </span>
            );
          } else {
            return <></>;
          }
        }
      },
    }),
    columnHelper.accessor("hisCode", {
      id: "hisCode",
      header: "HIS代码",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return <span>{row.getValue("hisCode")}</span>;
        }
      },
      enableSorting: true,
    }),
    columnHelper.accessor("drugname", {
      id: "drugname",
      header: "药品名称",
    }),
    columnHelper.accessor("priceSum", {
      id: "priceSum",
      header: "金额",
    }),
    columnHelper.accessor("amountSum", {
      id: "amountSum",
      header: "数量",
    }),
    columnHelper.accessor("amountUnit", {
      id: "amountUnit",
      header: "数量单位",
    }),
    columnHelper.accessor("manuName", {
      id: "manuName",
      header: "生产厂商",
      size: 200,
      minSize: 200,
    }),
    columnHelper.accessor("cadn", {
      id: "cadn",
      header: "通用名",
    }),
    columnHelper.display({
      header: "操作",
      id: "actions",
      cell: ({ row }) => {
        return (
          <>
            <DropdownMenu modal={false}>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="h-8 w-8 p-0">
                  <span className="sr-only">选项</span>
                  <MoreHorizontal className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                <DropdownMenuLabel></DropdownMenuLabel>
              </DropdownMenuContent>
            </DropdownMenu>
          </>
        );
      },
    }),
  ];

  const defaultValues = {
    startDate: new Date(),
    endDate: new Date(),
    hisCode: "",
  };

  // 表单部分
  const form = useForm<FormValuesT>({
    resolver: zodResolver(formSchema),
    defaultValues: defaultValues,
  });

  function onSubmit(values: z.infer<typeof formSchema>) {
    console.log(values);
    const params = new URLSearchParams();
    params.set("startDate", JSON.stringify(values.startDate));
    params.set("endDate", JSON.stringify(values.endDate));
    params.set("hisCode", JSON.stringify(values.hisCode));

    generateVbpStatsList(params.toString()).then(
      (res) => {
        console.log(res);
      },
      (err: any) => {
        console.log(err);
      }
    );
  }

  return (
    <PageContainer>
      <div
        className="w-full py-6 border p-3"
        style={{
          display: hasPermission(user, "vbp_day_stats", "{'GET'}")
            ? "block"
            : "hidden",
        }}
      >
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="flex items-center space-x-4"
          >
            <FormField
              control={form.control}
              name="startDate"
              render={({ field }) => (
                <FormItem>
                  {/* <FormLabel>开始时间</FormLabel> */}
                  <FormControl>
                    <CustomDatePicker
                      placeholder="开始时间"
                      value={field.value}
                      onChange={field.onChange}
                      startMonth={dayjs().subtract(2, "year").toDate()}
                      endMonth={dayjs().add(1, "year").toDate()}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="endDate"
              render={({ field }) => (
                <FormItem>
                  {/* <FormLabel>结束时间</FormLabel> */}
                  <FormControl>
                    <CustomDatePicker
                      placeholder="结束时间"
                      value={field.value}
                      onChange={field.onChange}
                      startMonth={dayjs().subtract(2, "years").toDate()}
                      endMonth={dayjs().add(1, "years").toDate()}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="hisCode"
              render={({ field }) => (
                <FormItem>
                  <Input />
                </FormItem>
              )}
            />
            <Button type="submit">生成</Button>
          </form>
        </Form>
      </div>
      <div className="space-y-4">
        <Separator />

        <CustomDndTable
          defaultFilterColumn="drugname"
          columns={columns}
          initColumnVisibility={{ select: false, id: false }}
          data={vbpBatchList}
          loading={loadingList}
          totalCount={totalCount}
          showImportButton={true}
          onSubmitFiles={handleUploadSubmit}
        />
      </div>
    </PageContainer>
  );
};

export default page;
